import Taro from '@tarojs/taro';
import {Image, View, Block} from '@tarojs/components';
import {connect} from "@tarojs/redux";
import {request, unite} from '../../../utils/index';
import './arrangingCourseyNext.scss';
import Go from "../../../asset/images/go.png";
import BgSelect from "../../../asset/myImages/bg_.png";
import BgSelect1 from "../../../asset/myImages/bg_1.png";
import BgSelect2 from "../../../asset/myImages/bg_2.png";
import SelectList from "../../../components/select-list/selectList";

class MyCoupon extends Taro.Component {
    config = {
        navigationBarTitleText: '排课',
        navigationBarBackgroundColor: '#ffffff',
    };

    state = {
        num: 0, //初始人数
        items: [], //课程
        roomWrap: [],//教室
        roomWrapTime: [], //教室时间
        classDate: '', //时间选择
        roomIs: [],//时间选择最多三个
    };

    temp = {
        on_status: false
    };

    componentDidShow() {
        const {setClassDate} = this.props;
        this.setState({
            classDate: setClassDate
        }, () => {
            const option = this.$router.params;
            if (option.id && option.id != "undefined") {
                console.log( option.id)
                this.alertInit(option.id); //课程详情
            }
            console.log(JSON.stringify(option));
            if (option.roomId != 'undefined') {
                this.alertInitNext(option.roomId); //教室详情
                this.InitTimeNext(option.roomId); //教室时间
            }
        })
    }

    //课程
    alertInit = (id) => {
        console.log(id);
        const params = {
            url: '/wx/coach/resClassRefDetail',
            data:{
                id,
            }
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    if (res && res.data) {
                        this.setState({
                            items: res.data
                        })
                    }
                }
            }
        })
    };

    //教室
    alertInitNext = (id) => {
        const {classDate} = this.state;
        const params = {
            url: '/wx/firstPage/getRoomDetail',
            data:{
                classDate,
                roomId: id,
            }
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    if (res && res.data) {
                        this.setState({
                            roomWrap: res.data
                        })
                    }
                }
            }
        })
    };

    //教室时间
    InitTimeNext = (id) => {
        const {classDate} = this.state;
        const params = {
            url: '/wx/coach/getEnableDispatchTimes',
            data:{
                classDate,
                roomId: id,
            }
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    if (res && res.data) {
                        this.setState({
                            roomWrapTime: res.data.dispatchTimes
                        })
                    }
                }
            }
        })
    };

    //时间选择
    getTimers = (time) => {
        let option = this.$router.params;
        console.log(time);
        this.setState({
            classDate: time,
            roomIs: [],
        }, () => {
            this.InitTimeNext(option.roomId);
        })
    };

    getSelectTime = (index, enable) => {
        if (enable) return;
        const {roomIs} = this.state;
        for(let i = 0; i < roomIs.length; i++){
            if (roomIs[i] == index) {
                this.setState(prevState => {
                    prevState.roomIs.splice(i, 1);
                    return {
                        roomIs: prevState.roomIs,
                    }
                });
                return;
            }
        }
        // if (roomIs.length >= 3) return;
        this.setState(prevState => {
            prevState.roomIs.push(index);
            return {
                roomIs: prevState.roomIs,
            }
        });
    };

    //跳转导航
    skipDaohang = () => {
        const {roomWrap} = this.state;
        if (Number(roomWrap.latitude) && Number(roomWrap.longitude)) {
            Taro.openLocation({
                latitude: Number(roomWrap.latitude),
                longitude: Number(roomWrap.longitude),
                name: roomWrap.roomName,
                address: roomWrap.address
            })
        } else {
            unite.showToast('该店铺暂无经纬度');
        }
    };

    //修改人数
    alertNum = (type) => {
        const {items} = this.state;
        this.setState(prevState => ({
           num: type ?  prevState.num >= items.studentNum ? prevState.num : prevState.num+1 : prevState.num == 0 ? 0 : prevState.num - 1
        }))
    };

    sumbit = () => {
        const option = this.$router.params;
        console.log(JSON.stringify(option));
        const {roomIs, roomWrapTime, classDate, items, num} = this.state;
        if (option.id == 'undefined') return unite.showToast('请选择课程');
        if (!option.roomId) return unite.showToast('请选择教室');
        if (roomIs.length == 0) return unite.showToast('请选择时间段');
        if (this.temp.on_status) return;
        this.temp.on_status = true;

        let roomTime = [];
        roomIs.forEach((item) => {
            roomTime.push({
                classBeginTime: roomWrapTime[item].classBeginTime,//上课时段开始时间
                classEndTime: roomWrapTime[item].classEndTime, //上课时段结束时间
            })
        });

        const params = {
            url: '/wx/coach/addClassDispatch',
            data:{
                classAttachId: items.classAttachId,  //课程附加属性ID
                classDispatchTimes: roomTime,
                classBeginTime: '06:00',
                classEndTime: '07:00',
                classDate: classDate, //classDate
                classId: items.classId, //	课程ID
                roomId: option.roomId, //教室ID
                classRefId: items.classRefId,
                subscribeNum: num,
            }
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    unite.showToast('添加成功');
                    setTimeout(() => {
                        Taro.navigateBack({delta: 1})
                    }, 1500)
                } else {
                    this.temp.on_status = false;
                }
            } else {
                this.temp.on_status = false;
            }
        })
    };

    render() {
        const {roomWrap, items, roomWrapTime, roomIs, num} = this.state;
        let option = this.$router.params;
        return (
            <View className="myPage">
                <View className="arranging-wrap">
                    {items.length != 0 ? (
                        <View className="arranging-kc-wrap" onClick={() => {Taro.redirectTo({url: '../select-coursey/selectCourse?roomId='+option.roomId})}}>
                            <View className="course-list flex-lr">
                                <Image className="course-img" mode="widthFix" src={items.customAvatars[0]}/>
                                <View className="course-content flex-lr">
                                    <View>
                                        <View className="course-name text-overflow">{items.className}</View>
                                        <View className="flex-l">
                                            <View className="course-g flex-center">{items.classScaleName}</View>
                                            <View>¥{items.price}/节</View>
                                        </View>
                                        {/*<View className="flex-l">*/}
                                        {/*    {items.labelNames.map((value, is) => (*/}
                                        {/*        <View className="course-gg flex-center" key={is}>{value}</View>*/}
                                        {/*    ))}*/}
                                        {/*</View>*/}
                                    </View>
                                    {/*<View className="course-btn flex-center">查看</View>*/}
                                </View>
                            </View>
                        </View>
                    ) : (
                        <View className="arranging-kc-wrap" onClick={() => {Taro.redirectTo({url: '../select-coursey/selectCourse?roomId='+option.roomId})}}>
                            <View className="name">1添加一门课程</View>
                            <View className="add-ke flex-center">+</View>
                        </View>
                    )}
                    {items.length != 0 &&(
                        <View className="select-num-wrap flex-lr">
                            <View>初始人数</View>
                            <View className="flex-r">
                                <View className="jian-icon jian flex-center" onClick={this.alertNum.bind(this, 0)}>-</View>
                                <View className="num">{num}/{items.studentNum}</View>
                                <View className="jian-icon flex-center" onClick={this.alertNum.bind(this, 1)}>+</View>
                            </View>
                        </View>
                    )}
                    {roomWrap.length != 0 ? (
                        <View className="arranging-kc-wrap">
                            <View className="flex-lr classRoom-wrap">
                                <View className="flex-l">
                                    <View className="heng"></View>
                                    <View>选中的教室</View>
                                </View>
                                <View className="flex-r" onClick={() => {Taro.redirectTo({url: '../select-map/selectMap?id='+option.id})}}>
                                    <View className="alert-classRoom">更换教室</View>
                                    <View className="arrow"></View>
                                </View>
                            </View>
                            <View className="classRoom-content-wrap">
                                <View className="class-top flex-lr">
                                    <View className="class-title flex-l">
                                        <Image className="head-img" src={roomWrap.avatar}/>
                                        <View className="content-title">
                                            <View className="name">{roomWrap.roomName}</View>
                                            <View className="text-overflow">{roomWrap.address}</View>
                                        </View>
                                    </View>
                                    <View className="go-map" onClick={this.skipDaohang}>
                                        <Image className="icon-img" src={Go}/>
                                        <View>去这里</View>
                                    </View>
                                </View>
                                <View className="classroom-contents">
                                    <SelectList onTimer={this.getTimers}/>
                                    <View className="timer-select-wrap flex-lr">
                                        {roomWrapTime.map((item, index) => (
                                            <View className={`time-item flex-center ${item.enable == 1 ? 'time-item-db' : ''} ${(item.enable == 0) ? 'time-item-db-one' : ''}`} key={index} onClick={this.getSelectTime.bind(this, index, item.enable)}>
                                                <View className="text">{item.classBeginTime +'-'+ item.classEndTime}</View>
                                                {roomIs.map((value, is) => (
                                                    <Block>
                                                        {value == index &&(
                                                            <Image className="bg-select" key={is} src={BgSelect}/>
                                                        )}
                                                    </Block>
                                                ))}
                                                {item.enable == 2 &&(
                                                    <Image className="bg-select" src={BgSelect1}/>
                                                )}
                                                {item.enable == 3 &&(
                                                    <Image className="bg-select" src={BgSelect2}/>
                                                )}
                                            </View>
                                        ))}
                                    </View>
                                </View>
                            </View>
                            <View className="flex-r status-names-content">
                                <View className="flex-r namex">
                                    <View className="red-quan yipai"></View>
                                    <View>已排课</View>
                                </View>
                                <View className="flex-r namex">
                                    <View className="red-quan daipai"></View>
                                    <View>待排课</View>
                                </View>
                                <View className="flex-r namex">
                                    <View className="red-quan"></View>
                                    <View>选中</View>
                                </View>
                            </View>
                            <View className="max-btn-wrap flex-center">
                                <View className="max-btn flex-center" onClick={this.sumbit}>确认上传</View>
                            </View>
                        </View>
                    ) : (
                        <View className="arranging-kc-wrap">
                            <View className="name">2选择一间教室</View>
                            <View className="add-ke flex-center" onClick={() => {Taro.redirectTo({url: '../select-map/selectMap?id='+option.id})}}>+</View>
                        </View>
                    )}
                </View>
            </View>
        )
    }
}

const mapStateToProps = state => {
    let {setClassDate} = state;
    return {
        setClassDate
    }
};

const mapDispatchToProps = {
};

export default connect(mapStateToProps, mapDispatchToProps)(MyCoupon);



